﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using SimpleForum.Data.Models;
using SimpleForum.Data.Repositories;

namespace SimpleForum.Data.Services
{
    public static class ConfigurationService
    {
        public static readonly string CacheKey = "SimpleForumConfig";

        public static bool AchievementsEnabled { get { return Get<bool>("AchievementsEnabled"); } }
        public static bool ReputationEnabled { get { return Get<bool>("ReputationEnabled"); } }
        public static bool OpenIDEnabled { get { return Get<bool>("OpenIDEnabled"); } }
        public static string ForumName { get { return Get<string>("ForumName"); } }
        public static string AvatarRelativePath { get { return Get<string>("AvatarRelativePath"); } }
        public static string Theme { get { return Get<string>("Theme"); } }
        public static string FromEmailAddress { get { return Get<string>("FromEmailAddress"); } }
        public static string EmailServer { get { return Get<string>("EmailServer"); } }

        public static T Get<T>(string Key)
        {
            List<Configuration> Configs = (List<Configuration>)HttpRuntime.Cache[CacheKey];

            if (Configs == null)
            {
                UpdateCache();
                Configs = (List<Configuration>)HttpRuntime.Cache[CacheKey];
            }

            Configuration Config = Configs.Single(x => x.Key == Key);

            if (typeof(T).ToString() == Config.Type)
            {
                try
                {
                    return (T)Convert.ChangeType(Config.Value, typeof(T));
                }
                catch
                {
                    return default(T);
                }

            }
            else return default(T);
        }

        public static void UpdateCache()
        {
            // fix me
            var Repository = new Repository<Configuration>(new DatabaseContextContainer());
            List<Configuration> Configurations = Repository.Get().ToList();

            HttpRuntime.Cache[CacheKey] = Configurations;
        }
    }
}